package xyz.hubery.match;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import xyz.hubery.match.impl.LimitMatchServiceImpl;
import xyz.hubery.stream.Source;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * 撮合交易服务工厂类
 */
@Component
@Slf4j
public class MatchServiceFactory {

    @Autowired
    private ApplicationContext applicationContext;

    private static MatchServiceFactory instance;

    @PostConstruct
    public void init() {
        instance = this;
        log.info(" MatchServiceFactory 初始化完成");
    }

    private static final Map<String, String> SERVICE_BEANS = new HashMap<>();

    static {
        SERVICE_BEANS.put(MatchStrategy.LIMIT_MATCH, "limitMatchServiceImpl");
        // 添加其他策略
    }

    public static MatchService getInstance(String matchServiceName) {
        if (instance == null) {
            throw new IllegalStateException("MatchServiceFactory 未初始化，请确保 Spring 容器已启动");
        }

        String beanName = SERVICE_BEANS.get(matchServiceName);
        if (beanName == null) {
            throw new IllegalArgumentException("不支持的匹配策略: " + matchServiceName);
        }

        try {
            return instance.applicationContext.getBean(beanName, MatchService.class);
        } catch (Exception e) {
            throw new RuntimeException("获取匹配服务失败: " + matchServiceName, e);
        }
    }
}